<?php
require_once("../includes/config.inc.php");
validate_admin();
$id = $_REQUEST['id'];
$subjectId = $_REQUEST['subjectId'];

if($_POST)
{
	@extract($_POST);
	// Edit Code
	$noerror=true;
	if(isFieldDuplicate($tableName='tbl_questions',$fieldName='question',$filedValue=$name,$autoIdName='id',$autoIdValue=$id,$isNullAllowed=false)) 
	{	
		$_SESSION['sessMsg'] = " Sorry, this Question ".$name." already exists. Please choose a different Question. ";
		$noerror=false;
	}
	if($noerror)
	{	
		if($id)
		{
			$sqlEdit = " update tbl_questions set
			question = '$question',
			subjectId = '$subjectId'
			where id ='$id'";
			executeQuery($sqlEdit);

			foreach($answer as $key=>$value)
			{
				$isRight = 0;
				if(($isCorrect[0]) == $key) {$isRight = 1;}
				$sqlIA = "update tbl_answers set
				answer = '$value',
				isRight = '$isRight'
				where id = '$key'
				";				
				executeQuery($sqlIA);
			}
			
			$_SESSION['sessMsg'] = "Detail Edited Successfully. ";
			header("location: questionManager.php?subjectId=$subjectId");
			exit();
		}
		else
		{
			// Add Code
			$sqlPA = " insert into tbl_questions 
			(
				question,
				subjectId,	
				status
			)
			values
			(
				'$question',
				'$subjectId',
				'1'
			)
			";

			executeQuery($sqlPA);	
			$questionId = mysql_insert_id();		

			foreach($answer as $key=>$value)
			{
				$isRight = 0;
				
				if(($isCorrect[0] - 1) == $key) {$isRight = 1;}
				$sqlIA = "insert into tbl_answers (questionId,answer,isRight)values('$questionId','$value','$isRight')";				
				executeQuery($sqlIA);
			}

			$_SESSION['sessMsg'] = " New Record Added Successfully. ";
			header("location: questionManager.php?subjectId=$subjectId");
			exit();
		}
	}		
}
			
if($id)
{
	$sqlPD = " select * from tbl_questions where id = '$id' ";
	$resPD = executeQuery($sqlPD);
	if($rowPD = mysql_fetch_array($resPD))
	{	
		@extract($rowPD);
	}
	
	$sqlA = "select * from tbl_answers where questionId = '$id' ";
	$resA = executeQuery($sqlA);
}
?>